<template>
    <div class="artist-management">
        <div class="header-actions">
            <el-button type="primary" @click="handleAdd" :icon="Plus">新增艺人</el-button>
        </div>
        <el-table
          :data="tableData"
          style="width: 100%"
          :row-class-name="tableRowClassName">
          <el-table-column
            prop="name"
            label="艺人(组合)名称">
          </el-table-column>
          <el-table-column
            prop="status"
            label="当前状态"
            sortable>
          </el-table-column>
          <el-table-column
            prop="fansCount"
            label="粉丝量"
            sortable>
          </el-table-column>
          <el-table-column
            prop="fansIncreaseLast30Days"
            label="粉丝净增量"
            sortable>
          </el-table-column>
          <el-table-column
            prop="revenueLast30Days"
            label="近30天营收"
            sortable>
          </el-table-column>
          <el-table-column
            prop="contractRemainingDays"
            label="距离续期"
            sortable>
          </el-table-column>
          <el-table-column
            prop="baseCity"
            label="驻地">
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(scope.row)">修改</el-button>
              <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 新增艺人对话框 -->
        <el-dialog 
          v-model="addDialogVisible" 
          title="新增艺人" 
          width="45%" 
          destroy-on-close
          top="5vh"
          class="artist-dialog">
          <div class="dialog-header-divider"></div>
          <div class="form-container">
            <el-form 
              :model="artistForm" 
              :rules="rules" 
              ref="artistFormRef" 
              label-width="110px" 
              class="artist-form"
              label-position="left">
              <el-form-item label="艺人名称" prop="name">
                <el-input 
                  v-model="artistForm.name" 
                  placeholder="请输入艺人名称"
                  prefix-icon="User">
                </el-input>
              </el-form-item>
              
              <el-form-item label="当前状态" prop="status">
                <el-select 
                  v-model="artistForm.status" 
                  placeholder="请选择状态" 
                  style="width: 100%"
                  prefix-icon="Flag">
                  <el-option 
                    v-for="item in stateOptions" 
                    :key="item" 
                    :label="item" 
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
              
              <el-form-item label="粉丝量" prop="fansCount">
                <el-input 
                  v-model.number="artistForm.fansCount" 
                  type="number" 
                  placeholder="请输入粉丝量"
                  prefix-icon="Star">
                </el-input>
              </el-form-item>
              
              <el-form-item label="粉丝净增量" prop="fansIncreaseLast30Days">
                <el-input 
                  v-model.number="artistForm.fansIncreaseLast30Days" 
                  type="number" 
                  placeholder="请输入粉丝净增量"
                  prefix-icon="TrendCharts">
                </el-input>
              </el-form-item>
              
              <el-form-item label="近30天营收" prop="revenueLast30Days">
                <el-input 
                  v-model.number="artistForm.revenueLast30Days" 
                  type="number" 
                  placeholder="请输入近30天营收"
                  prefix-icon="Money">
                </el-input>
              </el-form-item>
              
              <el-form-item label="距离续期" prop="contractRemainingDays">
                <el-input 
                  v-model.number="artistForm.contractRemainingDays" 
                  type="number" 
                  placeholder="请输入距离续期天数"
                  prefix-icon="Calendar">
                </el-input>
              </el-form-item>
              
              <el-form-item label="驻地" prop="baseCity">
                <el-autocomplete
                  v-model="artistForm.baseCity"
                  :fetch-suggestions="queryAddressSearch"
                  placeholder="请输入或选择驻地"
                  style="width: 100%"
                  prefix-icon="Location"
                ></el-autocomplete>
              </el-form-item>
            </el-form>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="addDialogVisible = false" :icon="Close">取消</el-button>
              <el-button type="primary" @click="submitArtistForm('artistFormRef')" :icon="Check">确认</el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 修改艺人对话框 -->
        <el-dialog 
          v-model="editDialogVisible" 
          title="修改艺人信息" 
          width="45%" 
          destroy-on-close
          top="5vh"
          class="artist-dialog">
          <div class="dialog-header-divider"></div>
          <div class="form-container">
            <el-form 
              :model="artistForm" 
              :rules="rules" 
              ref="editFormRef" 
              label-width="110px" 
              class="artist-form"
              label-position="left">
              <el-form-item label="艺人名称" prop="name">
                <el-input 
                  v-model="artistForm.name" 
                  placeholder="请输入艺人名称"
                  prefix-icon="User">
                </el-input>
              </el-form-item>
              
              <el-form-item label="当前状态" prop="status">
                <el-select 
                  v-model="artistForm.status" 
                  placeholder="请选择状态" 
                  style="width: 100%"
                  prefix-icon="Flag">
                  <el-option 
                    v-for="item in stateOptions" 
                    :key="item" 
                    :label="item" 
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
              
              <el-form-item label="粉丝量" prop="fansCount">
                <el-input 
                  v-model.number="artistForm.fansCount" 
                  type="number" 
                  placeholder="请输入粉丝量"
                  prefix-icon="Star">
                </el-input>
              </el-form-item>
              
              <el-form-item label="粉丝净增量" prop="fansIncreaseLast30Days">
                <el-input 
                  v-model.number="artistForm.fansIncreaseLast30Days" 
                  type="number" 
                  placeholder="请输入粉丝净增量"
                  prefix-icon="TrendCharts">
                </el-input>
              </el-form-item>
              
              <el-form-item label="近30天营收" prop="revenueLast30Days">
                <el-input 
                  v-model.number="artistForm.revenueLast30Days" 
                  type="number" 
                  placeholder="请输入近30天营收"
                  prefix-icon="Money">
                </el-input>
              </el-form-item>
              
              <el-form-item label="距离续期" prop="contractRemainingDays">
                <el-input 
                  v-model.number="artistForm.contractRemainingDays" 
                  type="number" 
                  placeholder="请输入距离续期天数"
                  prefix-icon="Calendar">
                </el-input>
              </el-form-item>
              
              <el-form-item label="驻地" prop="baseCity">
                <el-autocomplete
                  v-model="artistForm.baseCity"
                  :fetch-suggestions="queryAddressSearch"
                  placeholder="请输入或选择驻地"
                  style="width: 100%"
                  prefix-icon="Location"
                ></el-autocomplete>
              </el-form-item>
            </el-form>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="editDialogVisible = false" :icon="Close">取消</el-button>
              <el-button type="primary" @click="updateArtist('editFormRef')" :icon="Check">确认</el-button>
            </div>
          </template>
        </el-dialog>
    </div>
</template>
  
<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  
  .el-table .danger-row {
    background: #fef0f0;
  }
  
  .el-table .special-row {
    background: #e6f1ff;
  }

  .artist-management {
    padding: 20px;
  }

  .header-actions {
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .artist-form .el-form-item__label {
    font-weight: bold;
    color: #303133;
  }

  .artist-form .el-input-number {
    width: 100%;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 10px;
  }
  
  .artist-dialog .el-dialog__header {
    margin-right: 0;
    text-align: center;
    padding: 15px 20px 5px;
  }
  
  .artist-dialog .el-dialog__body {
    padding: 0px 20px 20px;
  }
  
  .artist-dialog .el-dialog__title {
    font-size: 18px;
    font-weight: bold;
    color: #409EFF;
  }
  
  .dialog-header-divider {
    height: 1px;
    background-color: #EBEEF5;
    margin-bottom: 15px;
  }
  
  .artist-form .el-input__inner,
  .artist-form .el-select .el-input__inner,
  .artist-form .el-autocomplete .el-input__inner {
    border-radius: 4px;
    height: 36px;
  }

  .artist-form .el-form-item {
    margin-bottom: 16px;
  }
  
  .form-container {
    max-width: 500px;
    margin: 0 auto;
  }
</style>
  
<script>
  import request from '@/utils/request'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import { 
    Plus, Edit, Delete, 
    User, Flag, Star, 
    TrendCharts, Money, Calendar, 
    Location, Close, Check 
  } from '@element-plus/icons-vue'
  
  export default {
    methods: {
      tableRowClassName({row}) {
        // 异常情况1: 状态为'签约中'或'休息中'
        // 异常情况2: fansIncreaseLast30Days小于-1000
        // 异常情况3: revenueLast30Days小于-100000
        // 异常情况4: contractRemainingDays小于60
        
        // 签约中的艺人高亮
        if (row.status === '签约中') {
          return 'special-row';
        }
        
        // 多重异常情况组合
        if ((row.fansIncreaseLast30Days < -1000 && row.revenueLast30Days < -100000) ||
            (row.fansIncreaseLast30Days < -1000 && row.contractRemainingDays < 60) ||
            (row.revenueLast30Days < -100000 && row.contractRemainingDays < 60)) {
          return 'danger-row';
        }
        
        // 单一异常情况
        if (row.fansIncreaseLast30Days < -1000 || row.revenueLast30Days < -100000 || row.contractRemainingDays < 60) {
          return 'warning-row';
        }
        
        // 正常情况
        return '';
      },
      getArtistInfo() {
        request.get('/getArtistInfo').then(res => {
          console.log(res.data)
          if (res.data.code === 200) {
            this.tableData = res.data.data
          } else {
            ElMessage.error('获取艺人信息失败')
          }
        }).catch(err => {
          console.error('获取艺人信息失败:', err)
          ElMessage.error('获取艺人信息失败')
        })
      },
      // 打开新增艺人对话框
      handleAdd() {
        this.artistForm = {
          name: '',
          status: '',
          fansCount: 0,
          fansIncreaseLast30Days: 0,
          revenueLast30Days: 0,
          contractRemainingDays: 0,
          baseCity: ''
        }
        this.addDialogVisible = true
        // 重置表单校验状态
        if (this.$refs.artistFormRef) {
          this.$refs.artistFormRef.resetFields()
        }
      },
      // 提交新增艺人表单
      submitArtistForm(formRef) {
        // 表单校验
        this.$refs[formRef].validate(valid => {
          if (!valid) {
            ElMessage.warning('请完善表单信息')
            return
          }
          
          // 检查艺人名称是否已存在
          const isArtistExists = this.tableData.some(artist => artist.name === this.artistForm.name)
          if (isArtistExists) {
            ElMessage.warning(`艺人"${this.artistForm.name}"已存在，不能重复添加`)
            return
          }

          request.post('/addArtist', this.artistForm).then(res => {
            if (res.data.code === 200) {
              // 添加成功，刷新数据
              ElMessage.success('添加艺人成功')
              this.getArtistInfo()
              // 关闭对话框
              this.addDialogVisible = false
            } else {
              ElMessage.error(res.data.msg || '添加艺人失败')
            }
          }).catch(err => {
            console.error('添加艺人失败:', err)
            ElMessage.error('添加艺人失败')
          })
        })
      },
      // 打开修改艺人对话框
      handleEdit(row) {
        // 复制一份数据，避免直接修改表格数据
        this.artistForm = JSON.parse(JSON.stringify(row))
        this.editingArtistId = row.id
        this.editDialogVisible = true
        // 重置表单校验状态
        if (this.$refs.editFormRef) {
          this.$refs.editFormRef.resetFields()
        }
      },
      // 更新艺人信息
      updateArtist(formRef) {
        // 表单校验
        this.$refs[formRef].validate(valid => {
          if (!valid) {
            ElMessage.warning('请完善表单信息')
            return
          }
          
          // 检查除了自己外，是否有重名艺人
          const isArtistExists = this.tableData.some(
            artist => artist.name === this.artistForm.name && artist.id !== this.editingArtistId
          )
          if (isArtistExists) {
            ElMessage.warning(`艺人"${this.artistForm.name}"已存在，请更换名称`)
            return
          }
        
          request.put(`/updateArtist/${this.editingArtistId}`, this.artistForm).then(res => {
            if (res.data.code === 200) {
              // 更新成功，刷新数据
              ElMessage.success('修改艺人成功')
              this.getArtistInfo()
              // 关闭对话框
              this.editDialogVisible = false
            } else {
              ElMessage.error(res.data.msg || '修改艺人失败')
            }
          }).catch(err => {
            console.error('更新艺人失败:', err)
            ElMessage.error('更新艺人失败')
          })
        })
      },
      // 删除艺人
      handleDelete(row) {
        ElMessageBox.confirm(
          `确定要删除"${row.name}"的记录吗？`,
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          // 用户确认删除
          request.delete(`/deleteArtist/${row.id}`).then(res => {
            if (res.data.code === 200) {
              // 删除成功，刷新数据
              ElMessage.success('删除艺人成功')
              this.getArtistInfo()
            } else {
              ElMessage.error(res.data.msg || '删除艺人失败')
            }
          }).catch(err => {
            console.error('删除艺人失败:', err)
            ElMessage.error('删除艺人失败')
          })
        }).catch(() => {
          // 用户取消删除
          ElMessage.info('已取消删除')
        })
      },
      // 驻地搜索建议
      queryAddressSearch(queryString, cb) {
        const addressList = [
          '北京', '上海', '广州', '深圳', '杭州',
          '南京', '成都', '重庆', '武汉', '西安',
          '长沙', '贵阳', '哈尔滨', '台北', '香港',
          '新加坡', '东京', '首尔', '纽约', '洛杉矶'
        ]
        
        const results = queryString
          ? addressList.filter(item => item.includes(queryString))
          : addressList
          
        // 格式化为组件需要的数据结构
        const suggestions = results.map(item => {
          return { value: item }
        })
        
        cb(suggestions)
      }
    },
    created() {
      this.getArtistInfo()
    },
    data() {
      return {
        tableData: [],
        addDialogVisible: false,
        editDialogVisible: false,
        editingArtistId: null,
        artistForm: {
          name: '',
          status: '',
          fansCount: 0,
          fansIncreaseLast30Days: 0,
          revenueLast30Days: 0,
          contractRemainingDays: 0,
          baseCity: ''
        },
        // 状态选项
        stateOptions: ['巡演中', '休息中', '创作中', '签约中'],
        // 表单验证规则
        rules: {
          name: [
            { required: true, message: '请输入艺人名称', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '请选择艺人状态', trigger: 'change' }
          ],
          fansCount: [
            { required: true, message: '请输入粉丝量', trigger: 'blur' },
            { type: 'number', message: '粉丝量必须为数字值', trigger: 'blur' }
          ],
          fansIncreaseLast30Days: [
            { required: true, message: '请输入粉丝净增量', trigger: 'blur' },
            { type: 'number', message: '粉丝净增量必须为数字值', trigger: 'blur' }
          ],
          revenueLast30Days: [
            { required: true, message: '请输入近30天营收', trigger: 'blur' },
            { type: 'number', message: '营收必须为数字值', trigger: 'blur' }
          ],
          contractRemainingDays: [
            { required: true, message: '请输入距离续期天数', trigger: 'blur' },
            { type: 'number', message: '天数必须为数字值', trigger: 'blur' }
          ],
          baseCity: [
            { required: true, message: '请输入或选择驻地', trigger: 'blur' }
          ]
        },
        Plus,
        Edit,
        Delete,
        User,
        Flag,
        Star,
        TrendCharts,
        Money,
        Calendar,
        Location,
        Close,
        Check
      }
    }
  }
</script>
  